//
//  Template.m
//  dao
//
//  Created by fangdi on 09-9-13.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "Template.h"
#import "/usr/include/sqlite3.h"
#import "DatabaseException.h"

static BOOL isLoaded;
static sqlite3 *database;

@implementation Template
-(id)init{
	if((self = [super init]) != nil){
		[self initDataBase];
		return self;
	}
	return nil;
}

-(void)query: (NSString *)sql{
	
}

-(void)update: (NSString *)sql{
	[self sqlite3Exec:sql];
}

-(void)remove: (NSString *)sql{
	[self sqlite3Exec:sql];
}

-(void)insert: (NSString *)sql{
	[self sqlite3Exec:sql];
}
@end

#pragma mark -
#pragma mark 以下都是私有方法
@interface Template(INIT)
-(void)initDataBase;
-(void)sqlite3Exec;
-(void)sqlite3Prepare;
@end
@implementation Template(INIT)
-(void)initDataBase{
	if(!isLoaded){
		NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDirectory = [path objectAtIndex:0];
		//TODO: 添加文件名字，从配置文件中读取
		NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"data.sqlite3"];
		if(sqlite3_open([filePath UTF8String], &database) != SQLITE_OK){
			sqlite3_close(database);
			NSException *exception = [DatabaseException exceptionWithName: @"DatabaseException."
																   reason: @"Database fails to initialize."
																 userInfo: nil];
			@throw exception;
		}else {
			[self initTables];
			[self initTablesData];
			isLoaded = YES;
		}
	}
}

-(void)sqlite3Exec: (NSString *)sql{
	char *errorMsg;
	if(sqlite3_exec(database, [sql UTF8String], nil, nil, &errorMsg) != SQLITE_OK){
		NSException *exception = [DatabaseException exceptionWithName:@"DatabaseException" 
															   reason:[[NSString alloc] initWithUTF8String:errorMsg] 
															 userInfo:nil];
		sqlite3_free(errorMsg);
		@throw exception;
	}
}

-(void)initTables{
	
}

-(void)initTablesData{
	
}
@end
